<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\manage\model\admin;

use buwang\base\BaseModel;

class CodeGenerateTable extends BaseModel
{
    /**
     * 数据表主键
     * @var string
     */
    protected $pk = 'id';

    /**
     * 模型名称
     * @var string
     */
    protected $name = 'code_generate_table';

    //设置json类型字段
    protected $json = ['menu', 'tree', 'relations', 'delete'];
    //设置JSON数据返回数组
    protected $jsonAssoc = true;

    /**
     * 关联数据表字段
     */
    public function tableColumn()
    {
        return $this->hasMany(CodeGenerateColumn::class, 'table_id', 'id');
    }

    /**
     * 初始化代码生成数据表信息
     * @param $tableData
     * @param $adminId
     * @return mixed
     */
    public static function initTable($tableData, $adminId)
    {
        return self::create([
            'table_name' => $tableData['name'],
            'table_comment' => $tableData['comment'],
            'template_type' => 0,
            'generate_type' => 0,
            'module_name' => 'adminapi',
            'admin_id' => $adminId,
            // 菜单配置
            'menu' => [
                'pid' => 0, // 父级菜单id
                'type' => 0, // 构建方式 0-手动添加 1-自动构建
                'name' => $tableData['comment'], // 菜单名称
            ],
            // 删除配置
            'delete' => [
                'type' => 0, // 删除类型
                'name' => 'delete_time', // 默认删除字段名
            ],
            // 关联配置
            'relations' => [],
            // 树形crud
            'tree' => []
        ]);
    }

    /**
     * 模板类型描述
     * @param $value
     * @param $data
     * @return mixed
     */
    public function getTemplateTypeDescAttr($value, $data)
    {
        $data_new = [
            0 => '单表(增删改查)',
            1 => '树表(增删改查)',
        ];
        if ($value === true) {
            return $data_new;
        }
        return $data_new[$data['template_type']] ?? '';
    }

    /**
     * 同步表字段
     */
    public static function syncColumnCodeGenerateTable($params)
    {
        // table 信息
        $table = self::findOrEmpty($params['id']);
        // 删除旧字段
        CodeGenerateColumn::whereIn('table_id', $table['id'])->delete();
        // 获取当前数据表字段信息
        $column = CodeGenerateColumn::getTableColumn($table['table_name']);
        // 创建新字段数据
        CodeGenerateColumn::initTableColumn($column, $table['id']);
        return true;
    }

    /**
     * 更新表字段
     * @param $params
     * @return bool
     */
    public static function editCodeGenerateTable($params)
    {
        // 格式化配置
        $options = self::formatTableData($params);
        // 更新主表-数据表信息
        self::update([
            'id' => $params['id'],
            'table_name' => $params['table_name'],
            'table_comment' => $params['table_comment'],
            'template_type' => $params['template_type'],
            'author' => $params['author'] ?? '',
            'remark' => $params['remark'] ?? '',
            'generate_type' => $params['generate_type'],
            'module_name' => $params['module_name'],
            'class_dir' => $params['class_dir'] ?? '',
            'class_comment' => $params['class_comment'] ?? '',
            'menu' => $options['menu'],
            'delete' => $options['delete'],
            'tree' => $options['tree'],
            'relations' => $options['relations'],
        ]);

        // 更新从表-数据表字段信息
        foreach ($params['table_column'] as $item) {
            CodeGenerateColumn::update([
                'id' => $item['id'],
                'column_comment' => $item['column_comment'] ?? '',
                'is_required' => $item['is_required'] ?? 0,
                'is_insert' => $item['is_insert'] ?? 0,
                'is_update' => $item['is_update'] ?? 0,
                'is_lists' => $item['is_lists'] ?? 0,
                'is_query' => $item['is_query'] ?? 0,
                'query_type' => $item['query_type'],
                'view_type' => $item['view_type'],
                'dict_type' => $item['dict_type'] ?? '',
            ]);
        }
        return true;
    }

    /**
     * 详情字段配置
     * @param $options
     * @return mixed
     */
    public static function formatTableData($options)
    {
        // 菜单配置
        $menuConfig = $options['menu'] ?? [];
        // 删除配置
        $deleteConfig = $options['delete'] ?? [];
        // 关联配置
        $relationsConfig = $options['relations'] ?? [];
        // 树表crud配置
        $treeConfig = $options['tree'] ?? [];

        $relations = [];
        foreach ($relationsConfig as $relation) {
            $relations[] = [
                'name' => $relation['name'] ?? '',
                'model' => $relation['model'] ?? '',
                'type' => $relation['type'] ?? 'has_one',
                'local_key' => $relation['local_key'] ?? 'id',
                'foreign_key' => $relation['foreign_key'] ?? 'id',
            ];
        }

        $options['menu'] = [
            'pid' => intval($menuConfig['pid'] ?? 0),
            'type' => intval($menuConfig['type'] ?? 0),
            'name' => !empty($menuConfig['name']) ? $menuConfig['name'] : $options['table_comment'],
        ];
        $options['delete'] = [
            'type' => intval($deleteConfig['type'] ?? 0),
            'name' => !empty($deleteConfig['name']) ? $deleteConfig['name'] : 'delete_time',
        ];
        $options['relations'] = $relations;
        $options['tree'] = [
            'tree_id' => $treeConfig['tree_id'] ?? "",
            'tree_pid' =>$treeConfig['tree_pid'] ?? "",
            'tree_name' => $treeConfig['tree_name'] ?? '',
        ];

        return $options;
    }

}